<template>
  <div class="customer-analysis-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客单分析</span>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :model="queryForm" label-width="120px" class="query-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数据库连接">
              <el-select 
                v-model="queryForm.databaseId" 
                placeholder="请选择数据库"
                style="width: 100%"
                @change="handleDatabaseChange"
              >
                <el-option
                  v-for="db in databaseList"
                  :key="db.id"
                  :label="db.name"
                  :value="db.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期区间">
              <el-date-picker
                v-model="queryForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="金额大于">
              <el-input-number
                v-model="queryForm.minAmount"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          v-loading="loading"
          :height="tableHeight"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="flowNo" label="单号" width="200" />
          <el-table-column prop="saleAmount" label="单据金额" width="120" align="right">
            <template #default="scope">
              ￥{{ scope.row.saleAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="operDate" label="操作时间" width="180" />
          <el-table-column prop="paymentCount" label="支付方式数量" width="120" align="center" />
          <el-table-column prop="payAmount" label="实收总额" width="120" align="right">
            <template #default="scope">
              ￥{{ scope.row.payAmount.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 汇总行 -->
        <div class="summary-bar">
          <div class="summary-item">
            <span class="summary-label">查询结果：</span>
            <span class="summary-value">共 <strong>{{ totalCount }}</strong> 条数据</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">单据金额合计：</span>
            <span class="summary-value total-amount">￥{{ totalSaleAmount.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">实收总额合计：</span>
            <span class="summary-value total-amount">￥{{ totalPayAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getDatabaseList } from '@/api/database'
import { API_BASE_URL } from '@/config/api'

interface DatabaseItem {
  id: number
  name: string
}

interface QueryForm {
  databaseId: number | null
  dateRange: string[]
  minAmount: number
}

interface TableRow {
  flowNo: string
  saleAmount: number
  operDate: string
  paymentCount: number
  payAmount: number
}

const loading = ref(false)
const tableHeight = ref(500)
const databaseList = ref<DatabaseItem[]>([])
const tableData = ref<TableRow[]>([])

const queryForm = reactive<QueryForm>({
  databaseId: null,
  dateRange: [],
  minAmount: 0
})

// 计算汇总数据
const totalCount = computed(() => tableData.value.length)
const totalSaleAmount = computed(() => 
  tableData.value.reduce((sum, item) => sum + item.saleAmount, 0)
)
const totalPayAmount = computed(() => 
  tableData.value.reduce((sum, item) => sum + item.payAmount, 0)
)

// 加载数据库列表
const loadDatabaseList = async () => {
  try {
    const res = await getDatabaseList()
    if (res.success && res.data) {
      databaseList.value = res.data
      // 默认选择第一个数据库
      if (databaseList.value.length > 0) {
        queryForm.databaseId = databaseList.value[0].id
      }
    }
  } catch (error) {
    console.error('加载数据库列表失败:', error)
  }
}

// 数据库切换
const handleDatabaseChange = (value: number) => {
  console.log('切换数据库:', value)
  // 清空表格数据
  tableData.value = []
}

// 查询
const handleQuery = async () => {
  if (!queryForm.databaseId) {
    ElMessage.warning('请选择数据库连接')
    return
  }

  if (!queryForm.dateRange || queryForm.dateRange.length !== 2) {
    ElMessage.warning('请选择日期区间')
    return
  }

  loading.value = true
  
  try {
    // 调用后端API
    const response = await fetch(`${API_BASE_URL}/api/report/customer-analysis`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        databaseId: queryForm.databaseId,
        startDate: queryForm.dateRange[0],
        endDate: queryForm.dateRange[1],
        minAmount: queryForm.minAmount
      })
    })

    const result = await response.json()
    
    if (result.success) {
      tableData.value = result.data || []
      ElMessage.success(`查询成功，共 ${tableData.value.length} 条数据`)
    } else {
      ElMessage.error(result.message || '查询失败')
      tableData.value = []
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  queryForm.dateRange = []
  queryForm.minAmount = 0
  tableData.value = []
}

onMounted(() => {
  loadDatabaseList()
  // 计算表格高度
  tableHeight.value = window.innerHeight - 400
})
</script>

<style scoped>
.customer-analysis-container {
  width: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.table-container {
  margin-top: 20px;
}

.summary-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 40px;
  margin-top: 16px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
}

.summary-value {
  font-size: 16px;
  color: #303133;
}

.summary-value strong {
  color: #409eff;
  font-size: 20px;
}

.total-amount {
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}
</style>
